import * as wasm from "WasmPack";


let test = wasm.GameState.new(Math.ceil(Math.random()*6));
let tid = null;

let processKeyEvent = function(key) {
    console.log("processKeyEvent: ", key);
    switch(key) {
        case "ArrowUp":
            test.key_up();
            break;
        case "ArrowLeft":
            test.key_left();
            break;
        case "ArrowRight":
            test.key_right();
            break;
        case "ArrowDown":
            clearInterval(tid);
            tid = setInterval(move, 50);
            break;
        case "Escape":
            clearInterval(tid);
            break;
    }
}

let move = function() {
    let idx = Math.ceil(Math.random()*6);
    if (!test.game_loop(idx)) {
        console.log("GAME ~~~~~~~~~~~~~~~ OVER");
        clearInterval(tid);
    }
}

let start = function() {
    test.init();
    document.addEventListener("keydown", e => processKeyEvent(e.key));
    document.onkeyup = function (ev) {
        console.log("KEY UP == ", ev.key);
        switch (ev.key) {
            case "ArrowDown":
                clearInterval(tid);
                tid = setInterval(move, 1000);
                break;
        }
    };

    tid = setInterval(move, 1000);

}

start();

